#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

enum
{
    SocketErr = 2,
    BindErr,//3
    ListenErr,//4
};

const int g_backlog = 10;

class Sock
{
public:
    Sock()
    {
    }
    ~Sock()
    {
    }

    //创建一个套接字
    void Socket()
    {
        //int socket(int __domain, int __type, int __protocol)
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            log(Fatal, "socker error, %s: %d", strerror(errno), errno);
            exit(SocketErr);
        }

        //允许立即重用本地地址和端口号
        //int setsockopt(int __fd, int __level, int __optname, const void *__optval, socklen_t __optlen)
        int opt = 1;
        setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    //服务端调用bind将当前的ip+port绑定到socket
    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);
        
        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            log(Fatal, "bind error, %s: %d", strerror(errno), errno);
            exit(BindErr);
        }
    }

    //服务端开始监听
    void Listen()
    {
        if (listen(_sockfd, g_backlog) < 0)
        {
            log(Fatal, "listen error, %s: %d", strerror(errno), errno);
            exit(ListenErr);
        }
    }

    //服务端接收客户端发来的连接请求 并 获取客户端的ip+port
    int Accept(std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(_sockfd, (struct sockaddr*)&peer, &len);
        if(newfd < 0)
        {
            log(Warning, "accept error, %s: %d", strerror(errno), errno);
            return -1;
        }

        //将peer.sin_addr中的网络字节序的二进制IP地址
        //转换为可读的字符串格式并存入ipstr
        char ipBuf[64]; 
        inet_ntop(AF_INET, &peer.sin_addr, ipBuf, sizeof(ipBuf));

        *clientip = ipBuf;
        *clientport = ntohs(peer.sin_port);

        return newfd;
    }

    //客户端向服务端发起连接请求
    bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n = connect(_sockfd, (struct sockaddr*)&peer, sizeof(peer));
        if(n == -1) 
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }

    void CloseFd()
    {
        close(_sockfd);
    }

    int getSocketFd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};
